package com.example.scaletest.batch;

import android.app.IntentService;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.example.scaletest.utils.NetConnHelper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by ZDZ on 2017/3/17.
 */
public class BatchService extends IntentService {

    private HttpURLConnection conn = null;
    public String PRODUCT_API ="http://10.103.246.33:8080/data/getProducts";//"http://10.103.246.33:8080/data/getProducts" ; // "http://139.220.193.149/test2/firm/getProduct";
    public String BATCH_API = "http://10.103.246.33:8080/data/getBatch";//"http://139.220.193.149/test2/firm/getBatch";
    private String finalResult = "";
    private String request = "";

    public BatchService(){
        super("BatchService");
    }

    public BatchService(String name){
        super(name);
    }

    @Override
    public void onCreate(){
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent){
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId){
        Log.d(this.getClass().getName(), "onStartCommand");
        return super.onStartCommand(intent, flags, startId);
    }

    public void postToUIThread(String message){
        final String mes = message;
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), mes, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void onHandleIntent(Intent intent){
        String result = "";
        request = intent.getExtras().getString("request");
        if(NetConnHelper.isConn(BatchService.this)){
            try{
                if (request.indexOf("firm_id") != -1)//shenmeyisi
                    result = downloadData(PRODUCT_API);
                else
                    result = downloadData(BATCH_API);
                if (result != ""){
                    Log.d("downloadData",result);
                    Intent intentBroadcast = new Intent();
                    intentBroadcast.setAction("ACTION_UPDATE_UI");
                    intentBroadcast.putExtra("jsonData", result);
                    sendBroadcast(intentBroadcast);
                }else{
                    postToUIThread("下载失败，请重新下载");
                }
            }catch(Exception e){
                e.printStackTrace();
                postToUIThread("下载失败，请重新下载");
            }
        }else{
            postToUIThread("没有网络，请检查网络情况");
        }
    }
    public String downloadData(String url){
        BufferedReader reader;
        OutputStreamWriter writer;
        try{
            conn = (HttpURLConnection) new URL(url).openConnection();
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            //conn.setRequestProperty("content-type","text/html:charset=GBk");
            conn.setRequestProperty("content-type","application/json;charset=utf-8");
            writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(request);
            writer.flush();
            writer.close();

            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder result = new StringBuilder();
            String line;
            while((line =reader.readLine()) != null){
                result.append(line);
            }
            finalResult = result.toString();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            if (conn != null){
                conn.disconnect();
            }
        }
        return finalResult;
    }
}
